using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using FirstTea.Domain.Entities;
using FirstTea.Domain.Repositories;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstTea.Application.Services
{
    public class OrderService : IOrderService
    {
        private readonly IRepository<Order> _orderRepo;
        public OrderService(IRepository<Order> orderRepo)
        {
            _orderRepo = orderRepo;
        }
        public async Task<OrderDto?> GetByIdAsync(Guid id)
        {
            var order = await _orderRepo.GetByIdAsync(id);
            if (order == null) return null;
            return new OrderDto { Id = order.Id, UserId = order.UserId, Status = order.Status, TotalPrice = order.TotalAmount };
        }
        public async Task<IEnumerable<OrderDto>> GetAllAsync()
        {
            var orders = await _orderRepo.GetAllAsync();
            return orders.Select(o => new OrderDto { Id = o.Id, UserId = o.UserId, Status = o.Status, TotalPrice = o.TotalAmount });
        }
        public async Task CreateAsync(OrderDto dto)
        {
            var order = new Order { UserId = dto.UserId, Status = dto.Status, TotalAmount = dto.TotalPrice };
            await _orderRepo.AddAsync(order);
            await _orderRepo.SaveChangesAsync();
        }
        public async Task UpdateAsync(OrderDto dto)
        {
            if (dto == null) throw new ArgumentNullException(nameof(dto));
            var order = await _orderRepo.GetByIdAsync(dto.Id);
            if (order == null) return;
            order.Status = dto.Status;
            order.TotalAmount = dto.TotalPrice;
            await _orderRepo.UpdateAsync(order);
            await _orderRepo.SaveChangesAsync();
        }
        public async Task DeleteAsync(Guid id)
        {
            await _orderRepo.DeleteAsync(id);
            await _orderRepo.SaveChangesAsync();
        }

    }
}
